package com.fsts.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * 接收文件类
 * 
 *
 */
public class ReceiveFile implements Runnable {

	@Override
	public void run() {
		DataInputStream in = null;
		DataOutputStream out = null;
		FileOutputStream fileOutputStream = null;
		Socket socket = null;
		try {
			ServerSocket serverSocket = new ServerSocket(9966);
			while (true) {
				socket = serverSocket.accept();
				System.out.println("客户端发送信息>>>>>");
				in = new DataInputStream(socket.getInputStream());
				out = new DataOutputStream(socket.getOutputStream());
				String result = in.readUTF();
				System.out.println("读取客户端数据：" + result);
				System.out.println("返回信息给客户端成功>>>>>");
				out.writeUTF("已经收到信息");
				byte[] b = new byte[1000000];
				StringBuffer saveFile = new StringBuffer("/"); // 文件保存路径
				saveFile.append(in.readUTF());
				File file = new File(saveFile.toString());
				fileOutputStream = new FileOutputStream(file);
				System.out.println("收到文件，正在下载文件>>>>>");
				long length = in.readLong();
				DecimalFormat format = new DecimalFormat("###,##0");
				format.setMinimumFractionDigits(2);
				double stat = new Date().getTime();
				while (true) {
					int read = in.read(b);
					if (read == -1) {
						break;
					}
					fileOutputStream.write(b, 0, read);
					System.out
							.println("已经接收："
									+ format
											.format(((double) file.length() / length) * 100)
									+ "%");
				}
				double end = new Date().getTime();
				System.out.println("消耗时间：" + (end - stat) / 1000);
				System.out.println("接受文件完成>>>>");

				fileOutputStream.flush();
				out.flush();

			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
				fileOutputStream.close();
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
